package com.controller;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.ibatis.executor.ReuseExecutor;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import com.alibaba.fastjson.JSON;
import com.service.UserLoginService;
import com.utils.Des;
import com.utils.ObjectUtils;
import com.utils.Ret;

@Controller
public class UserLoginController {

	private final Logger log = Logger.getLogger(UserLoginController.class); 
	@Autowired
	UserLoginService userLoginService;

	@RequestMapping(value = "/userlogin.do")
	public void login(HttpServletRequest request,
			HttpServletResponse response,PrintWriter out,
			Model mode) throws IOException {

		Map<String,Object> result = new HashMap<String,Object>();
		Ret ret = new Ret();
		Des des = new Des();
		try {
			String ucode = des.strDec(ObjectUtils.getStrVal(request.getParameter("ucode")),"key", null,null);// 用户名
			
			String pwd = des.strDec(ObjectUtils.getStrVal(request.getParameter("pwd")),"key", null,null);// 密码
			
			String p_code = request.getParameter("code");
			String code = "";
			if("".equals(p_code) || null == p_code){
				code = "-1";
			}else{
				code = des.strDec(ObjectUtils.getStrVal(request.getParameter("code")),"key", null,null);//验证码
			}
			
			ret = userLoginService.doLogin(code, ucode, pwd, request);
			
		} catch (Exception e) {
			e.printStackTrace();
			ret.setStatusCode("500");
			ret.setMessage("登录失败！");
			out.print(ret.toJsonString());
			out.flush();
			out.close();
		}
		
		result.put("rcode", ret.getStatusCode());
		result.put("message", ret.getMessage());
		result.put("ucode", request.getSession().getAttribute("usercode"));
		result.put("uname", request.getSession().getAttribute("username"));
		out.print(JSON.toJSON(result));
		out.flush();
		out.close();
		
	}
	
	@RequestMapping("doRegist.do")
	public void doRegist(@RequestParam("zjh") String zjh,
			@RequestParam("xm") String xm,
			@RequestParam("pwd") String pwd,
			@RequestParam("pwd2") String pwd2,
			Ret ret,PrintWriter out){
		
		Des des = new Des();
		zjh = des.strDec(zjh, "key", null,null);
		xm = des.strDec(xm, "key", null,null);
		pwd = des.strDec(pwd, "key", null,null);
		pwd2 = des.strDec(pwd2, "key", null,null);
		Map<String,Object> result = new HashMap<String,Object>();
		try {
			result = userLoginService.doRegist(zjh,xm, pwd,pwd2);
		} catch (Exception e) {
			e.printStackTrace();
			ret.setStatusCode("500");
			ret.setMessage("更新失败！");
		}
		
		out.print(JSON.toJSONString(result));
		out.flush();
		out.close();
		
	}


}
